﻿


using HbcServerProcess.Interfaces;
using HbcServerProcess.Models;
using IotContract.Consts;
using IotContract.Dtos.Clients;
using IotContract.Dtos.Clients.Equips;
using IotContract.Dtos.Servers;
using IotContract.Dtos.Servers.Process;
using IotContract.Dtos.Servers.Pushs;
using IotContract.Enums;
using IotContract.Extensions;
using IotContract.Interfaces;
using IotContract.Interfaces.Fmt;
using IotContract.Interfaces.Process;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XT.Common.Enums;
using XT.Common.Extensions;
using XT.Common.Services;

namespace HbcServerProcess.DataProcess;
/// <summary>
/// 物流线
/// </summary>
public class CvDataProcess : IServerProcessHandle
{
    private readonly IServerMainManager _mainProcess;
    private readonly IProcessDataService _processDataService;
    private readonly ILogService _logService;
    private readonly IRemoteHttpService _remoteHttpService;
    public CvDataProcess(IServerMainManager serverMainManager,IProcessDataService processDataService,ILogService logService,IRemoteHttpService remoteHttpService)
    {
        _mainProcess = serverMainManager;
        _processDataService = processDataService;
        _remoteHttpService = remoteHttpService;
        _logService= logService;
    }

    public string ProcessName { get; set; } = HbcServerConst.ProcessName;
    public IotEquipType ProcessType { get; set; } = IotEquipType.CV;

    private ConcurrentBag<IotEquipWarnDto> _warns = new ConcurrentBag<IotEquipWarnDto>();
    /// <summary>
    /// 托盘Job
    /// </summary>
    public ConcurrentDictionary<int, string> _trayJobDic { get; set; } = new ConcurrentDictionary<int, string>();

    public async Task<bool> ParsingData()
    {
        // 获取数据
       var equips=  await _mainProcess.GetEquips<PushSiemensDto>(new IotContract.Models.Clients.ClientRequestCommand
        {
            RequestType = IotEquipType.CV.ToString(),
            ProtobufType = IotProtobufType.HBC_SIEMENS_S7.ToString()
        });
        // 获取扫码枪
        var bcrDic = _processDataService.Bcrs;
        
        List<PushEquipTag> tags= new List<PushEquipTag>();
        foreach(var equip in equips)
        {
            tags.AddRange(equip.Tags);
        }

        // tags根据TagNum分组,TagNum=UnitNum
       var tagDic= tags.ToLookup(x => x.TagNum).ToDictionary(x => x.Key, y => y.ToList());

        var cvUnitDic = _processDataService.CvUnitTags;
        Parallel.ForEach(tagDic.Keys, x =>
        {
            var tagNum = x.To<int>();
            // 设备号
            var tags = tagDic[x];
            CvUnitTagDto unitTag = null;
            if (cvUnitDic.ContainsKey(tagNum))
            {
                unitTag = cvUnitDic[tagNum];
            }
            else
            {
                unitTag = new CvUnitTagDto();
                unitTag.TagNum = tagNum;
                var equip = equips.FirstOrDefault(x => x.Id == tags.FirstOrDefault()?.EquipInfoId);
                unitTag.EquipNum = equip.Num;
                unitTag.EquipId = equip.Id;
                unitTag.ProtobufType = equip.ProtobufType;
              cvUnitDic.TryAdd(tagNum, unitTag);
            }
          
            // 赋值扫码枪
            if(bcrDic.ContainsKey(tagNum))
            {
                unitTag.UseBcr = true;
                unitTag.Bcrs = bcrDic[tagNum];
            }
          
            SetUnitTag(unitTag, tags);
          

            
        });

        return true;
    }
    /// <summary>
    /// 设置unit的值
    /// </summary>
    /// <param name="unitTag"></param>
    private void SetUnitTag(CvUnitTagDto unitTag,List<PushEquipTag> tags)
    {
        unitTag.Tags = tags;
        Parallel.ForEach(tags, x =>
        {
            int.TryParse(x.Value, out int result);
            switch (x.TagProperty)
            {
                case "BCR_READY":
                    {
                        bool bcrReady = result == 1; ;
                        unitTag.IsBcrReady = bcrReady;
                        break;
                    }
                case "KEY_SWITCH_AUTO":
                    {
                        if (result == 0)
                        {
                            unitTag.ManualSameCount++;
                            // 重复10次以上，打手动
                            if (unitTag.ManualSameCount >= 10)
                            {
                                unitTag.IsManual = true;
                                unitTag.ManualSameCount = 10;
                            }
                        }
                        else
                        {
                            unitTag.ManualSameCount = 0;
                            unitTag.IsManual = false;
                        }




                        break;
                    }
                case "JOB_NUMBER":
                    {


                        unitTag.JobNumber = result;
                        // 点位刷新时间
                        unitTag.ReadTime = x.ReadTime;
                        break;
                    }
                case "JOB_TYPE":
                    {
                        unitTag.JobType = result;
                        break;
                    }
                case "ERROR_CODE":
                    {


                        unitTag.ErrorCode = result;
                        break;
                    }
                case "CARRI_EXIST":
                    {
                       

                        if (result == 1 && !unitTag.IsExistTray1)
                        {
                            unitTag.TrayInTime = DateTime.Now;
                        }
                        if (result == 0)
                        {
                            unitTag.TrayInTime = null;
                            unitTag.TrayOnTime = 0;
                        }
                        if (unitTag.TrayInTime != null)
                        {
                            unitTag.TrayOnTime = Math.Round(DateTime.Now.Subtract(unitTag.TrayInTime.Value).TotalMinutes, 0);
                        }
                        unitTag.IsExistTray1 = result == 1;

                        break;

                    }
                case "CARRI_EXIST_2F":
                    {


                        unitTag.IsExistTray2 = result == 1;
                        break;

                    }
                case "CARRI_EXIST_3F":
                    {


                        unitTag.IsExistTray3 = result == 1;
                        break;
                    }
                case "CARRI_EXIST_4F":
                    {


                        unitTag.IsExistTray4 = result == 1;
                        break;

                    }
                case "CARRI_EXIST_5F":
                    {


                        unitTag.IsExistTray5 = result == 1;
                        break;
                    }
                case "CARRI_EXIST_6F":
                    {



                        unitTag.IsExistTray6 = result == 1;
                        break;
                    }
              
                // 目的地
                case "DEST_NUM":
                    {
                        unitTag.Dest = result;
                        break;
                    }

                // 托盘类型
                case "TRAY_TYPE":
                    {
                       
                        unitTag.TrayType = result;
                        break;
                    }
                // 写入状态
                case "ACTIVE":
                    {

                        unitTag.Active = result;
                        break;
                    }
                // 碟盘完成
                case "STACK_OUT":
                    {
                        unitTag.UseMagazine = true;
                        unitTag.MagazineOut = result == 1;
                        break;
                    }

            }

        });      
    }
    /// <summary>
    /// 开始处理数据
    /// </summary>
    /// <returns></returns>
    public async Task<bool> ProcessData()
    {
        foreach(var unitTag in _processDataService.CvUnitTags.Values)
        {


            await ProcessMagazine(unitTag);

            // 确定是扫码枪
            if (unitTag.UseBcr)
            {
                // bcr准备好、物流线上存在托盘
                if (unitTag.IsExistTray1)
                {
                    if (unitTag.IsBcrReady && unitTag.JobNumber > 0)
                    {
                        // 直接验证停留时长,时长>2s再扫码
                        if (unitTag.TrayInTime != null)
                        {
                            if (DateTime.Now.Subtract(unitTag.TrayInTime.Value).TotalSeconds <= 1)
                            {
                                continue;
                            }
                        }

                        // 验证是否提交扫码
                        if (!ValidateBcrCommit(unitTag))
                        {
                            continue;
                        }

                        var bcrs = _processDataService.Bcrs.GetValueOrDefault(unitTag.TagNum);
                        if (bcrs == null || bcrs.Count() == 0 || !bcrs[0].Connection)
                        {
                            continue;
                        }
                        // 拥有错误码，新托盘过来了
                        if (unitTag.ErrorJobNumber > 0 && unitTag.JobNumber != unitTag.ErrorJobNumber)
                        {
                            _processDataService.ClearBcr(unitTag, false);
                            continue;
                        }
                        if (unitTag.BcrCommit == 0 && !unitTag.IsReadBcr)
                        {
                            // 不再进行扫码，已经进行过提交
                            if (unitTag.Tray1 == unitTag.Tray1Old && unitTag.Tray1.IsNotNullOrEmpty())
                            {
                                if (unitTag.JobNumber == unitTag.OriginJobNumber)
                                {
                                    continue;
                                }
                                else if (unitTag.JobNumber == unitTag.BcrCommitJob)
                                {
                                    continue;
                                }
                                else if (unitTag.Dest != unitTag.TagNum)
                                {
                                    continue;
                                }
                                else
                                {

                                    unitTag.Times++;
                                    if (unitTag.Times > 2)
                                    {
                                        await _logService.LogContent($"等候3次后开始清空 TagNumber {unitTag.TagNum}", LogEnum.Info, unitTag.TagNum.ToString());
                                        _processDataService.ClearBcr(unitTag, false);
                                        unitTag.Times = 0;
                                    }
                                    continue;

                                }
                            }


                            unitTag.IsReadBcr = true;
                            // 控制扫码枪进行扫码
                            bool isRead =await _processDataService.ReadBcr(unitTag);

                            if (!isRead)
                            {
                                unitTag.IsBcrReady = false;
                                // 读取扫码枪数据
                                await Value(unitTag);
                            }
                            await _logService.LogContent($"开始进行扫码 IsRead {isRead} TagNumber {unitTag.TagNum} Bcr {bcrs.FirstOrDefault()?.BindNum} {unitTag.IsExistTray1} {unitTag.IsExistTray2} {unitTag.IsExistTray3} {unitTag.IsExistTray4} {unitTag.IsExistTray5} {unitTag.IsExistTray6}", LogEnum.Info, unitTag.TagNum.ToString());

                        }
                        else
                        {

                            // 读取扫码枪数据
                            await Value(unitTag);



                        }
                    }
                }
                // 物流线上不存在托盘，清空历史值
                else
                {
                    //// 正在读取，无法清空条码
                    //if (unitTag.IsReadBcr)
                    //{
                    //    continue;
                    //}
                    if (unitTag.BcrCommit == 0)
                    {

                        _processDataService.ClearBcr(unitTag, false);
                    }
                }

            }
            else
            {
                // 不是扫码枪
                SetTrayByJob(unitTag, 0);

            }
        }
        return true;
    }

    /// <summary>
    /// 重新进行扫码
    /// </summary>
    /// <param name="unitTag"></param>
    private async Task ReCallBcr(CvUnitTagDto unitTag)
    {
        unitTag.RetryCount++;
        // 错误次数超限，重扫
        if (unitTag.RetryCount > 30 && unitTag.BcrCommitJob != unitTag.JobNumber && unitTag.JobNumber > 0)
        {
            if (unitTag.Dest <= unitTag.TagNum || unitTag.Dest - unitTag.TagNum <= 2)
            {
                await _logService.LogContent($"扫码后超过30s无法提交，重新进行扫码 {unitTag.TagNum}", LogEnum.Info, unitTag.TagNum.ToString());
                unitTag.BcrCommit = 0;
                unitTag.IsReadBcr = false;
                unitTag.RetryCount = 0;
                unitTag.ErrorMaxReadBcr = unitTag.MaxReadBcr;
            }

        }

    }
    /// <summary>
    /// 读取扫码数据
    /// </summary>
    /// <param name="unitTag"></param>
    /// <returns></returns>
    private async Task Value(CvUnitTagDto unitTag)
    {
        if (unitTag.BcrCommit == 1)
        {
            return;
        }
        // 开线程进行提交
        Task.Factory.StartNew(async () =>
        {


            var bcrs = _processDataService.Bcrs.GetValueOrDefault(unitTag.TagNum);

            ConcurrentDictionary<int, string> trayDic = new ConcurrentDictionary<int, string>();



            int tag = 0;
            int readOKCount = 0;






            if (unitTag.IsExistTray1)
            {

                tag++;
                var bcr = bcrs.FirstOrDefault(x => x.OrderNum == 1);
                if (bcr != null && bcr.ReadingStep == BcrProcessStepType.Read_OK)
                {
                    readOKCount++;
                    // 相同标志，读取数据
                    if (bcr.WriteId == unitTag.BcrID && bcr.WriteId.IsNotNullOrEmpty() && bcr.Value.IsNotNullOrEmpty())
                    {

                        unitTag.Tray1 = bcr.Value;


                        if (bcr.IsReadOK)
                        {

                            if (unitTag.Tray1 != unitTag.Tray1Old)
                            {
                                trayDic.TryAdd(1, bcr.Value);

                            }



                        }

                    }

                }
            }


            if (unitTag.IsExistTray2)
            {

                tag++;

                var bcr = bcrs.FirstOrDefault(x => x.OrderNum == 2);
                if (bcr != null && bcr.ReadingStep == BcrProcessStepType.Read_OK && bcr.Value.IsNotNullOrEmpty())
                {
                    readOKCount++;
                    // 相同标志，读取数据
                    if (bcr.WriteId == unitTag.BcrID && bcr.WriteId.IsNotNullOrEmpty())
                    {

                        unitTag.Tray2 = bcr.Value;


                        if (bcr.IsReadOK)
                        {

                            if (unitTag.Tray2 != unitTag.Tray2Old)
                            {
                                trayDic.TryAdd(2, bcr.Value);
                            }


                        }

                    }

                }
            }


            if (unitTag.IsExistTray3)
            {

                tag++;
                var bcr = bcrs.FirstOrDefault(x => x.OrderNum == 3);
                if (bcr != null && bcr.ReadingStep == BcrProcessStepType.Read_OK)
                {
                    readOKCount++;
                    // 相同标志，读取数据
                    if (bcr.WriteId == unitTag.BcrID && bcr.WriteId.IsNotNullOrEmpty() && bcr.Value.IsNotNullOrEmpty())
                    {

                        unitTag.Tray3 = bcr.Value;


                        if (bcr.IsReadOK)
                        {

                            if (unitTag.Tray3 != unitTag.Tray3Old)
                            {
                                trayDic.TryAdd(3, bcr.Value);
                            }

                        }

                    }

                }
            }

            if (unitTag.IsExistTray4)
            {

                tag++;
                var bcr = bcrs.FirstOrDefault(x => x.OrderNum == 4);
                if (bcr != null && bcr.ReadingStep == BcrProcessStepType.Read_OK && bcr.Value.IsNotNullOrEmpty())
                {
                    readOKCount++;
                    // 相同标志，读取数据
                    if (bcr.WriteId == unitTag.BcrID && bcr.WriteId.IsNotNullOrEmpty())
                    {

                        unitTag.Tray4 = bcr.Value;


                        if (bcr.IsReadOK)
                        {

                            if (unitTag.Tray4 != unitTag.Tray4)
                            {
                                trayDic.TryAdd(4, bcr.Value);
                            }

                        }

                    }


                }

            }

            if (unitTag.IsExistTray5)
            {
                tag++;
                var bcr = bcrs.FirstOrDefault(x => x.OrderNum == 5);
                if (bcr != null && bcr.ReadingStep == BcrProcessStepType.Read_OK && bcr.Value.IsNotNullOrEmpty())
                {
                    readOKCount++;
                    // 相同标志，读取数据
                    if (bcr.WriteId == unitTag.BcrID && bcr.WriteId.IsNotNullOrEmpty())
                    {

                        unitTag.Tray5 = bcr.Value;


                        if (bcr.IsReadOK)
                        {

                            if (unitTag.Tray5 != unitTag.Tray5Old)
                            {
                                trayDic.TryAdd(5, bcr.Value);
                            }

                        }

                    }

                }

            }

            if (unitTag.IsExistTray6)
            {
                tag++;
                var bcr = bcrs.FirstOrDefault(x => x.OrderNum == 6);
                if (bcr != null && bcr.ReadingStep == BcrProcessStepType.Read_OK && bcr.Value.IsNotNullOrEmpty())
                {
                    readOKCount++;
                    // 相同标志，读取数据
                    if (bcr.WriteId == unitTag.BcrID && bcr.WriteId.IsNotNullOrEmpty())
                    {

                        unitTag.Tray6 = bcr.Value;


                        if (bcr.IsReadOK)
                        {

                            if (unitTag.Tray6 != unitTag.Tray6Old)
                            {
                                trayDic.TryAdd(6, bcr.Value);
                            }

                        }

                    }

                }

            }

            unitTag.ReadOkBcr = readOKCount;

            if (trayDic.Count == tag && tag > 0 && unitTag.MaxReadBcr == tag && readOKCount == tag && unitTag.JobNumber > 0)
            {

                if (unitTag.BcrCommit == 1 || unitTag.BcrCommitTimes >= 1) return;

              
                if (trayDic.Keys.Max() != trayDic.Count)
                {
                    await ReCallBcr(unitTag);
                    return;
                }

                // 扫码枪15后重扫，如果光电不一样，不提交
                if (unitTag.ErrorMaxReadBcr > 0 && unitTag.MaxReadBcr < unitTag.ErrorMaxReadBcr)
                {
                    await ReCallBcr(unitTag);
                    return;
                }
                unitTag.BcrCommit = 1;
                List<string> trays = new List<string>();
                foreach (var key in trayDic.Keys.OrderBy(x => x))
                {
                    trays.Add(trayDic[key]);
                }
                unitTag.Trays = trays;


                // 扫码成功，进行服务调用，通知调度系统进行操作
                var result = await _remoteHttpService.CommitBcrResult(unitTag, trays);
                if (result.Flag && result.Data != null)
                {

                  
                    unitTag.OriginJobNumber = unitTag.JobNumber;
                    unitTag.Message = String.Empty;
                    await _logService.LogContent($"扫码提交成功，获取物流写入任务 {result.Data.JobNumber} 目的地 {result.Data.DestNum}", LogEnum.Info, unitTag.TagNum.ToString());
                    var msg = await _processDataService.WriteCvAddr(result.Data);
                    if (msg.IsNotNullOrEmpty())
                    {
                        unitTag.Message = msg;

                        unitTag.BcrCommitTimes++;

                        _warns.Add(new IotEquipWarnDto
                        {
                            EquipNum = unitTag.EquipNum,
                            EquipId = unitTag.EquipId,
                            ProtobufType = IotProtobufType.HBC_SIEMENS_S7.ToString(),
                            ErrorCode = $"{unitTag.TagNum} {String.Join(',', trays)}{IotMsgConst.CvCommitError},{msg}",
                            ErrorTime = DateTime.Now
                        });
                       

                        unitTag.ErrorJobNumber = unitTag.JobNumber;
                        unitTag.BcrCommit = 0;
                        return;
                    }

                    SetTrayByJob(unitTag, result.Data.JobNumber);

                    // 写入成功后，读取物流线数据
                    unitTag.BcrCommitJob = result.Data.JobNumber;
                    unitTag.Tray1Old = unitTag.Tray1;
                    unitTag.Tray2Old = unitTag.Tray2;
                    unitTag.Tray3Old = unitTag.Tray3;
                    unitTag.Tray4Old = unitTag.Tray4;
                    unitTag.Tray5Old = unitTag.Tray5;
                    unitTag.Tray6Old = unitTag.Tray6;

                    unitTag.BcrOldID = unitTag.BcrID;

                    unitTag.BcrID = Guid.NewGuid().ToString();

                    unitTag.IsReadBcr = false;
                    unitTag.ErrorJobNumber = 0;
                    unitTag.ErrorMaxReadBcr = 0;
                    unitTag.BcrCommit = 0;
                    unitTag.RetryCount = 0;
                    unitTag.BcrCommitTimes = 0;


                }
                else
                {

                    unitTag.Message = result.Msg;

                    if (unitTag.Message.IsNullOrEmpty())
                    {
                        unitTag.Message = IotMsgConst.CvCommitError;
                    }
                    
                    unitTag.BcrCommitTimes++;


                    _warns.Add(new IotEquipWarnDto
                    {
                        EquipNum = unitTag.EquipNum,
                        EquipId = unitTag.EquipId,
                        ProtobufType = IotProtobufType.HBC_SIEMENS_S7.ToString(),
                        ErrorCode = $"{unitTag.TagNum} {String.Join(',', trays)}commit to fms error,{result.Msg}",
                        ErrorTime = DateTime.Now
                    });
                


                    unitTag.ErrorJobNumber = unitTag.JobNumber;
                    unitTag.BcrCommit = 0;
                }




            }
            else
            {
                await ReCallBcr(unitTag);
            }
        });





    }

    public void SetTrayByJob(CvUnitTagDto unitTag, int jobNumber)
    {
        if (!unitTag.IsExistTray1 && jobNumber == 0)
        {
            unitTag.Tray1 = unitTag.Tray2 = unitTag.Tray3 = unitTag.Tray4 = unitTag.Tray5 = unitTag.Tray6 = "";
            return;
        }

        // 是扫码枪
        if (unitTag.UseBcr)
        {
            // 重新赋值
            if (jobNumber > 0 && unitTag.Trays != null && unitTag.Trays.Count > 0)
            {
                if (!_trayJobDic.ContainsKey(jobNumber))
                {
                    if (_trayJobDic.Count > 100000)
                    {
                        _trayJobDic.TryRemove(_trayJobDic.FirstOrDefault().Key, out _);
                    }
                    _trayJobDic.TryAdd(jobNumber, string.Join(',', unitTag.Trays));
                    return;
                }
                else
                {
                    _trayJobDic[jobNumber] = string.Join(',', unitTag.Trays);
                    return;
                }
            }

        }
        // 不是扫码枪，寻找 托盘号
        else
        {
            if (unitTag.JobNumber > 0)
            {
                if (!_trayJobDic.ContainsKey(unitTag.JobNumber))
                {
                    return;
                }
                var tray = _trayJobDic[unitTag.JobNumber];

                if (tray.IsNotNullOrEmpty())
                {
                    var trays = tray.Split(",");
                    unitTag.Tray1 = trays[0];
                    if (trays.Length > 1)
                    {
                        unitTag.Tray2 = trays[1];
                    }
                    if (trays.Length > 2)
                    {
                        unitTag.Tray3 = trays[2];
                    }
                    if (trays.Length > 3)
                    {
                        unitTag.Tray4 = trays[3];
                    }
                    if (trays.Length > 4)
                    {
                        unitTag.Tray5 = trays[4];
                    }
                    if (trays.Length > 5)
                    {
                        unitTag.Tray6 = trays[5];
                    }
                }

            }
        }



    }
    /// <summary>
    /// 叠盘相关逻辑
    /// </summary>
    /// <param name="unitTag"></param>
    /// <returns></returns>
    private async Task ProcessMagazine(CvUnitTagDto unitTag)
    {
        if (unitTag.UseMagazine)
        {
            // 碟盘机确认完成
            if (unitTag.MagazineOut != unitTag.MagazineOutOld)
            {
                if (!unitTag.MagazineOut)
                {
                    await _logService.LogContent($"{unitTag.TagNum} 叠盘信号消失，收到信号 {unitTag.StackOutTime} ,信号消失时间 {DateTime.Now}", LogEnum.Info, unitTag.TagNum.ToString());
                    // _serverDataService.WriteMagazine(unitTag, 0);
                    unitTag.MagazineOutOld = unitTag.MagazineOut;
                    unitTag.StackOutTime = null;
                }
                else
                {
                    if (unitTag.StackOutTime == null)
                    {
                        unitTag.StackOutTime = DateTime.Now;

                    }
                    else
                    {

                        unitTag.MagazineOutOld = unitTag.MagazineOut;

                        Task.Factory.StartNew(async () =>
                        {
                            await _logService.LogContent($"{unitTag.TagNum} 叠盘完成，收到信号 {unitTag.StackOutTime} ,调用时间 {DateTime.Now}", LogEnum.Info, unitTag.TagNum.ToString());


                            var result = await _remoteHttpService.CommitMagazine(unitTag.TagNum.To<int>());
                            if (result.Flag)
                            {
                                var tag= unitTag.GetTagByProperty("MAGAZINE_OUT_RES");
                                if (tag != null)
                                {

                                    tag.Value = "1";
                                    bool wResult =await _processDataService.WriteCvData(tag);
                                    await _logService.LogContent($"{unitTag.TagNum} 叠盘完成，调用成功，写入物流线 {wResult}", LogEnum.Info, unitTag.TagNum.ToString());
                                }
                               
                            }
                            else
                            {

                                unitTag.MagazineOutOld = false;
                                await _logService.LogContent($"{unitTag.TagNum} {IotMsgConst.CvMagazineError} {result.Msg}", LogEnum.Error, unitTag.TagNum.ToString());
                            }
                        });

                    }

                }
            }
            else
            {
                if (!unitTag.MagazineOut)
                {
                    unitTag.StackOutTime = null;
                }
                else
                {
                    // 仍然处于碟盘完成的状态
                    // 15s后再调用一次
                    if (unitTag.StackOutTime != null && DateTime.Now.Subtract(unitTag.StackOutTime.Value).TotalSeconds >= 15)
                    {
                        var tag = unitTag.GetTagByProperty("MAGAZINE_OUT_RES");
                        if (tag != null)
                        {
                            tag.Value = "1";
                            bool writeResult =await _processDataService.WriteCvData(tag);

                            await _logService.LogContent($"{unitTag.TagNum} 叠盘完成，再次写入物流线 {writeResult}", LogEnum.Info, unitTag.TagNum.ToString());

                            unitTag.StackOutTime = DateTime.Now;
                        }
                      
                    }
                }

            }
        }
    }

    /// <summary>
    /// 验证是否可以提交扫码
    /// </summary>
    /// <param name="ecsUnitTag"></param>
    /// <returns></returns>
    private bool ValidateBcrCommit(CvUnitTagDto ecsUnitTag)
    {
        if (ecsUnitTag.TagNum == 30636)
        {
           var tag= _processDataService.CvUnitTags.GetValueOrDefault(30642);
            var tag1 = _processDataService.CvUnitTags.GetValueOrDefault(30638);
            

            if (tag != null && tag1 != null)
            {
                if (tag.IsExistTray1 && tag1.IsExistTray1)
                {
                    return false;
                }
            }

            return true;

        }
        else if (new int[] { 22740, 22744, 22194 }.Contains(ecsUnitTag.TagNum))
        {
            //目的地址和站台相差>2 不进行扫码
            if (Math.Abs(ecsUnitTag.TagNum - ecsUnitTag.Dest) > 2)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        else
        {
            return true;
        }
    }


    public async Task<bool> ProcessOrder()
    {
        return true;
    }

    public async Task<bool> ProcessWarn()
    {
        // 上传报警
        if(_warns.Count > 0)
        {
            _warns.ForEach(x =>
            {
                x.ProtobufType = IotProtobufType.HBC_SIEMENS_S7.ToString();
            });
           await _mainProcess.AddWarns(_warns);
           _warns.Clear();
        }
        return true;
    }

    public bool Stop()
    {
        _processDataService.CvUnitTags.Clear();
        return true;
    }
}
